package com.liuyucheng.rabbitmq.normal.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {

    public static final String host = "192.168.56.10";
    public static final String queueName = "queue001";

    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost(host);//默认是localhost
        factory.setPort(5672);
        factory.setVirtualHost("lycvhost");//vhost
        factory.setUsername("liuyucheng");//用户名
        factory.setPassword("123123");
        //3.创建连接 Connection
        Connection connection = factory.newConnection();
        //4.创建通道 Channel
        Channel channel = connection.createChannel();
        //5.创建队列 Queue
        /**
         * String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
         * 1.队列名称
         * 2.是否持久化
         * 3.是否独占,只能有一个消费者监听这个队列,当Connection关闭时,是否删除队列
         * 4.是否自动删除,当没有Consumer时,自动删除掉
         * 5.参数
         */
        channel.queueDeclare(
                queueName, //如果没有一个名为hello_world的队列,就会创建一个,否则不会创建
                true,
                false,
                false,
                null
        );
        //6.发送消息
        /**
         * String exchange, String routingKey, BasicProperties props, byte[] body
         * 1.exchange 交换机名称,简单模式下交换机会使用默认的""
         * 2.routingKey 路由名称
         * 3.props 配置信息
         * 4.body 发送消息数据
         */
        for (int i = 0; i < 10; i++) {
            String body = "第"+i+"条消息";
            channel.basicPublish("",queueName,null,body.getBytes());
        }
        //释放资源
        channel.close();
        connection.close();

    }
}
